// 模块加载----------------------
const logger = require('log4js').getLogger("index");

/**
 * data analysis
 * @param {*} data
 * @param {*} socket
 * @param {*} callback
 */
function parse(data, socket, callback) {
    if (data.length == 0) {
        return null;
    }
    var request = {};
    try {
        let command = data[2];
        if (socket.sno != undefined) {
            request.sno = socket.sno;
        }
        request.cmd = command;
        if (command != 0x61) logger.info('[ woshi ]:', data);
        switch (command) {
            case 0x60:
                request.sno = Uint8ArrayToHexString(data.slice(17, 33));
                request.nums = 8;
                request.sversion = '1.0';
                request.card = '13800138000';
                break;
            case 0x61:
                break;
            //借充电宝结果 00 11 65 01 74 11 22 33 44 03 01 52 4c 31 41 7c 00 00 64
            case 0x64:
                request.dnolist = data.slice(10);
                break
            case 0x65:
                request.position = data[9];
                request.success = data[10];
                request.dno = getBatteryId(data.slice(11, 19));
                break;
            //归还成功 0010 66 01 41 11223344 01 524c31417c000052
            case 0x66:
                request.position = data[9];
                request.dno = getBatteryId(data.slice(10, 18));
                break;
            case 0x80:
                request.position = data[9];
                request.success = data[10];
                request.dno = getBatteryId(data.slice(11, 19));
                break;
        }
        callback(socket, request);
    } catch (error) {
        console.log(error);
        return null;
    }
}

function Uint8ArrayToHexString(data) {
    var res = "";
    for (var i = 0; i < data.length; i++) {
        res += String.fromCharCode(data[i]);
    }
    return res
}

function getBatteryId(data) {
    //WSBA
    let str = '';
    for (let i = 0; i < 4; i++) {
        str += PrefixInteger(data[i + 4].toString(16), 2)
    }
    return Uint8ArrayToHexString(data.slice(0, 4)) + str;
}

/**
 * @param {*} num
 * @param {*} length
 */
function PrefixInteger(num, length) {
    return (Array(length).join('0') + num.toString(16)).slice(-length);
}


module.exports = {
    parse: parse,
    PrefixInteger: PrefixInteger,
    getBatteryId: getBatteryId
}

